// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2005-6-30

#include "stdafx.h"
#include "tm_shutdownroom.h"
#include <common/svr_base/svr_asyncqueue.h>
#include <common/svr_base/db_utility.h>
#include "msvr_server.h"
#include "msvr_room.h"
#include "msvr_user.h"

namespace JoyServer
{

// class CJoyTmShutdownRoom

CJoyTmShutdownRoom::CJoyTmShutdownRoom()
{
    m_server    = NULL;
}

CJoyTmShutdownRoom::~CJoyTmShutdownRoom()
{
}

bool CJoyTmShutdownRoom::Create(CJoyMainServer* pServer)
{
    m_server    = pServer;

    if(!__super::Create(&pServer->m_timer, 1000))
    {
        return false;
    }
    return true;
}

void CJoyTmShutdownRoom::Destroy()
{
    __super::Destroy();

}

void CJoyTmShutdownRoom::SendInfo(CShutdownInfo* pInfo)
{
	pInfo;
}

void CJoyTmShutdownRoom::ClearInfo(CShutdownInfo* pInfo)
{
    CJoyMainRoom* pRoom = m_server->GetRoom(pInfo->m_roomId);
    delete pInfo;
    if(pRoom == NULL)
    {
        return;
    }

    {
        CJoyAutoCS gate(pRoom->m_userLock);

        POSITION pos = pRoom->m_userIds.GetStartPosition();
        while(pos != NULL)
        {
            CJoyUser* ju;
            UINT uid;
            pRoom->m_userIds.GetNextAssoc(pos, uid, ju);
            CJoyMainUser* u = (CJoyMainUser*)ju;
            u->Kick(JoyMessage::Error_RoomClosed);
        }
    }

    CJoyDbSession onlineSess;
    if(!JoyOpenDbSession(m_server, onlineSess, m_server->GetOnlineDbSource()))
    {
        return;
    }

    CJoyDbCommand rs;
    if(!JoyInvokeCommand(m_server, onlineSess, rs,
        L"remove_room",
        pRoom->m_roomId))
    {
        // return false;
    }
}

CJoyTmShutdownRoom::CShutdownInfo* CJoyTmShutdownRoom::PeekInfo()
{
    CJoyAutoCS gate(m_shutdownLock);
    if(m_shutdownList.IsEmpty())
    {
        return NULL;
    }
    return m_shutdownList.RemoveHead();
}

void CJoyTmShutdownRoom::AddInfo(CShutdownInfo* pInfo)
{
    CJoyAutoCS gate(m_shutdownLock);
    m_shutdownList.AddTail(pInfo);
}

void CJoyTmShutdownRoom::AddRoom(UINT roomId, UINT delay, const CString& note, DWORD noteDelay)
{
    CJoyMainRoom* pRoom = m_server->GetRoom(roomId);
    if(pRoom == NULL)
    {
        return;
    }
    pRoom->m_closing = true;

    CShutdownInfo* pInfo = new CShutdownInfo();
    pInfo->m_start  = GetTickCount();
    pInfo->m_delay  = delay;
    pInfo->m_roomId = roomId;
    pInfo->m_note   = note;
    pInfo->m_lastNote = pInfo->m_start-noteDelay;
    pInfo->m_noteDelay= noteDelay;
    SendInfo(pInfo);
    AddInfo(pInfo);
}

void CJoyTmShutdownRoom::OnExecute()
{
    CShutdownInfo* pInfo = PeekInfo();
    if(pInfo == NULL)
    {
        return;
    }
    if(::GetTickCount() > pInfo->m_start + pInfo->m_delay)
    {
        ClearInfo(pInfo);
        return;
    }
    SendInfo(pInfo);
    AddInfo(pInfo);
}

} // namespace JoyServer